package com.suray.wcs.web.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suray.basic.wcs.path.core.Node;
import com.suray.basic.wcs.path.enums.NodeType;
import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.enmus.BusinessType;
import com.suray.wcs.service.core.util.LockNodeManager;
import com.suray.wcs.service.system.entity.NodeDB;
import com.suray.wcs.service.system.entity.RgvDB;
import com.suray.wcs.service.system.entity.RgvTestDB;
import com.suray.wcs.service.system.entity.ScadaDB;
import com.suray.wcs.service.system.mapper.DeviceManagerMapper;
import com.suray.wcs.service.system.service.impl.RgvTestDBServiceImpl;
import com.suray.wcs.service.system.service.impl.ScadaDBSerciceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/rgvtest")
@CrossOrigin(value = "*", allowCredentials = "true")
public class RgvTestController extends BaseController {
    @Autowired
    RgvTestDBServiceImpl rgvTestDBService;
    @Autowired
    ScadaDBSerciceImpl scadaDBSercice;
    /**
     * 查询小车信息
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('rgvtest:query')")
    @GetMapping(value = "/queryRgvTestInfo")
    @ApiOperation(value = "查询小车测试信息")
    public TableDataInfo queryRgvInfo(RgvTestDB rgvTestDB) {
        startPage();
        List<RgvTestDB> rgvTestList = rgvTestDBService.getRgvTestList(rgvTestDB);
        if (!CollectionUtils.isEmpty(rgvTestList)) {
            for (RgvTestDB testDB : rgvTestList) {
                ScadaDB scadaDB= scadaDBSercice.getScadaDBByRgvNo(testDB.getRgvNo());
                if(scadaDB==null){
                    testDB.setAccumulatedMileage(0);
                    testDB.setReversalTimes(0);
                }else {
                    testDB.setAccumulatedMileage(scadaDB.getTravelDistance());
                    testDB.setReversalTimes(scadaDB.getOilDriveExecCount());
                }
                rgvTestDBService.updateRgvTest(testDB);
            }
        }
        return getDataTable(rgvTestList);
    }

    /*
     * 获取小车信息
     */
    @RequestMapping(value = "/getRgvTestByNo/{rgvId}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询小车信息")
    public ResponseData getRgvByNo(@PathVariable Integer rgvId) {
        if (rgvId == null) {
            return ResponseData.error("请选择小车");
        }
        RgvTestDB rgvTestDB = rgvTestDBService.getRgvTestDBByNo(rgvId);
        ScadaDB scadaDB= scadaDBSercice.getScadaDBByRgvNo(rgvTestDB.getRgvNo());
        if(scadaDB==null){
            rgvTestDB.setAccumulatedMileage(0);
            rgvTestDB.setReversalTimes(0);
        }else {
            rgvTestDB.setAccumulatedMileage(scadaDB.getTravelDistance());
            rgvTestDB.setReversalTimes(scadaDB.getOilDriveExecCount());
        }
        rgvTestDBService.updateRgvTest(rgvTestDB);
        return ResponseData.success("小车信息查询完成", rgvTestDB);
    }

    /**
     * 添加小车
     *
     * @param rgvTestDB
     * @return
     */
    @PreAuthorize("@ss.hasPermi('rgvTest:add')")
    @Log(title = "测试管理", method = "新增小车数据", businessType = BusinessType.INSERT)
    @PostMapping(value = "/insertRgvTestInfo")
    @ApiOperation("新增小车数据")
    public ResponseData insertRgvInfo(@Validated @RequestBody RgvTestDB rgvTestDB) {
        if (rgvTestDBService.checkSerialNoUnique(rgvTestDB)) {
            return ResponseData.error("新增测试小车'" + rgvTestDB.getRgvNo() + "'失败，小车序列号（编号）已存在");
        }
        if (rgvTestDBService.addRgvTest(rgvTestDB)) {
            return ResponseData.success(rgvTestDB.getRgvSerialNumber() + "号小车添加成功");
        } else {
            return ResponseData.error(rgvTestDB.getRgvSerialNumber() + "号小车添加失败");
        }
    }

    /**
     * 切换小车满足测试条件
     */
    @PreAuthorize("@ss.hasPermi('rgvtest:edit')")
    @Log(title = "测试管理", method = "修改满足测试条件", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateRgvSatisfy")
    @ApiOperation(value = "修改满足测试条件")
    public ResponseData updateSwitch(@RequestBody RgvTestDB rgvTestDB) {
        try{
            RgvTestDB updateRgv=rgvTestDBService.getRgvTestDBByNo(rgvTestDB.getRgvId());
            updateRgv.setIsCompliance(rgvTestDB.getIsCompliance());
            boolean flag = rgvTestDBService.updateById(updateRgv);
            if (flag) {
                return ResponseData.success("修改成功");
            } else {
                return ResponseData.error("修改失败");
            }
        }catch (IllegalStateException e) {
            return ResponseData.error("设备号为 " + rgvTestDB.getRgvId() + " 的小车不存在", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("修改失败");
        }
    }
    @PreAuthorize("@ss.hasPermi('rgvtest:edit')")
    @Log(title = "测试管理", method = "修改小车信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateRgvTestInfo")
    @ApiOperation(value = "修改小车信息")
    public ResponseData updateRgvInfo(@Validated @RequestBody RgvTestDB rgvTestDB) {
        try{
            boolean flag = rgvTestDBService.updateRgvTest(rgvTestDB);
            if (flag) {
                return ResponseData.success("修改成功");
            } else {
                return ResponseData.error("修改失败");
            }
        }catch (IllegalStateException e) {
            return ResponseData.error("设备号为 " + rgvTestDB.getRgvId() + " 的小车不存在", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("修改失败");
        }
    }
    /**
     * 删除测试小车
     *
     * @param rgvIds
     * @return
     */
    @Log(title = "测试管理", method = "删除测试小车", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteRgvTest/{rgvIds}")
    @ApiOperation(value = "删除测试小车")
    @PreAuthorize("@ss.hasPermi('rgvtest:remove')")
    public ResponseData deletePlcInfo(@PathVariable Long[] rgvIds) {

        return toAjax(rgvTestDBService.removeByIds(Arrays.asList(rgvIds)));
    }
}
